import { Component, OnInit } from '@angular/core';
import {environment} from "../../../../environments/environment";
import {ActivatedRoute, Router} from "@angular/router";
import {PublicService} from "../../../services/public.service";
import {StorageService} from "../../../services/storage.service";
import {EventBusService} from "../../../services/event-bus.service";
import {Message, TreeNode} from "primeng/primeng";
import {InventorymaintenanceService} from "../../inventorymaintenance.service";
import {PUblicMethod} from "../../public/PUblicMethod";

@Component({
  selector: 'app-malfunction-close-inventory',
  templateUrl: './malfunction-close-inventory.component.html',
  styleUrls: ['./malfunction-close-inventory.component.scss']
})
export class MalfunctionCloseInventoryComponent implements OnInit {
  sid: string;
  initStatus = '';                       // 故障单状态
  malfNumber = '';                       // 服务单号

  malSourceOptins: any = [];             // 可选来源数据
  malSource = '';                        // 来源
  malImpactOptions: any = [];            // 影响度可选数据
  malImpact = '';                        // 影响度
  malUrgencyOptions: any = [];           // 紧急度可选数据
  malUrgency = '';                       // 紧急度
  malLevelOptions: any = [];             // 故障级别选项
  malLevel = '';                         // 故障级别
  malfPrority = '';                      // 优先级
  malDepPersonOptions: any = [];         // 分配个人可选数据
  malDepPerson = '';                     // 分配个人

  malStatus = '新建';                    // 状态
  reporter: TreeNode[] = [];             // 报告人
  zh: any;
  dealTime: Date;                        // 受理时间
  occurTime: Date;                       // 发生时间
  // deadline: Date;                     // 最终期限
  malDeadline = '';                      // 最终期限

  malTitle = '';                         // 故障单标题
  malDesc = '';                          // 故障单描述
  uploadedFiles = [];
  uploadRes = [];                        // 上传成功返回的文件路径对象
  ip: string;                            // 127.0.0.1:80
  message: Message[] = [];               // 交互提示弹出框
  msg: Message[] = [];                   // 验证弹出框

  belongSystem: TreeNode[] = [];         // 所属系统
  locationOccur: TreeNode[] = [];        // 发生地点
  relativeCategore: TreeNode[] = [];     // 关联目录
  relativeEquip: TreeNode[] = [];        // 关联设备编号
  selectedDepartment: TreeNode[] = [];   // 分配至部门
  departementDisplay: boolean;           // 树显示控制
  filesTree4: TreeNode[];                // 树的可选值
  selected: TreeNode[];                  // 树的选中值
  dialogHeader: string;                  // 组织树弹框标题
  currentTreeName: string;               // 当前要加载的树
  selectedMode: string;                  // 树的选择模式

  startDealTime = PUblicMethod.formateEnrtyTime(new Date());

  malCloseOptions: any = [];
  malClose = '';
  malCloseTime  = '';

  paper: Object = {
    'sid': '',
    'close_code':  ''
  };

  constructor(private maintenanceService: InventorymaintenanceService,
              private router: Router,
              private storageService: StorageService,
              private publicService: PublicService,
              private activatedRouter: ActivatedRoute,
              private eventBusService: EventBusService) { }

  ngOnInit() {
    this.sid = this.activatedRouter.snapshot.paramMap.get('id');
    this.initTrick(this.sid);
    this.initStatus = this.activatedRouter.snapshot.paramMap.get('status');
    this.maintenanceService.getFlowChart(this.initStatus).subscribe(res => {
      this.eventBusService.maintenance.next(res);
    });
    console.log(this.activatedRouter.snapshot.paramMap.get('id'));
    console.log(this.activatedRouter.snapshot.paramMap.get('status'));
    this.zh = new PUblicMethod().initZh();
    this.dealTime = new Date();
    this.getOptions();
    this.getDepPerson();
    this.departementDisplay = false;
    this.ip = environment.url.management;
    this.malCloseOptions = [
      {name: '成功解决', code: 'NY'},
      {name: '临时解决', code: 'RM'},
      {name: '不成功', code: 'LDN'},
      {name: '撤销', code: 'IST'}
    ];
  }
  initTrick(s) {
    this.maintenanceService.getTrick(s).subscribe(res => {
      console.log(res);
      let data = res['data'];
      if (res['errcode'] === '00000') {
        this.malfNumber = data['sid'];
        this.malSource = data['fromx'];
        this.malStatus = data['status'];
        this.reporter['label'] = data['submitter'];
        this.reporter['father'] = data['submitter_org'];
        this.reporter['remark'] = data['phone'];
        this.dealTime = data['accept_time'];
        this.occurTime = data['occurrence_time'];
        this.malDeadline = data['deadline'];
        this.malImpact = data['influence'];
        this.malUrgency = data['urgency'];
        this.malfPrority = data['priority'];
        this.malLevel = data['level'];
        this.belongSystem['label'] = data['bt_system'];
        this.locationOccur['label'] = data['addr'];
        this.malTitle = data['title'];
        this.malDesc = data['content'];
        this.relativeCategore['label'] = data['service'];
        this.relativeEquip['label'] = data['devices'];
        this.selectedDepartment['label'] = data['assign_org_name'];
        this.malDepPerson = data['reassign_per_name'];

      }else {
        this.message = [];
        this.message.push({severity: 'error', summary: '消息提示', detail: `获取故障单信息失败${res}`});
      }
    });
  }
  getOptions() {
    this.maintenanceService.getParamOptions().subscribe(res => {
      if (!res) {
        this.malSourceOptins = [];
        this.malImpactOptions = [];
        this.malUrgencyOptions = [];
        this.malLevelOptions = [];
      }else {
        this.malSourceOptins = res['来源'];
        this.malImpactOptions = res['影响度'];
        this.malUrgencyOptions = res['紧急度'];
        this.malLevelOptions = res['故障级别'];
      }
    });
  }
  onBeforeUpload(event) {
    let token = this.storageService.getToken('token');
    event.formData.append('access_token', token);
  }
  onUpload(event) {
    let xhrRespose = JSON.parse(event.xhr.response);
    if ( xhrRespose.errcode && xhrRespose.errcode === '00000' ) {
      this.uploadRes = xhrRespose['datas'];
      this.message = [];
      this.message.push({severity: 'success', summary: '消息提示', detail: '上传成功'});
    }else {
      this.message = [];
      this.message.push({severity: 'error', summary: '消息提示', detail: `上传失败${xhrRespose.errmsg}`});
    }
  }
  // 部门组织树模态框
  showTreeDialog(which: string) {
    this.currentTreeName = which;
    this.selected = [];
    this.filesTree4 = [];
    this.departementDisplay = true;
    switch (which) {
      case 'reporter':
        this.dialogHeader = '请选择报告人';
        this.selectedMode = 'single';
        this.maintenanceService.getDepartmentDatas().subscribe(res => {
          this.filesTree4 = res;
        });
        break;
      case 'belongSystem':
        this.dialogHeader = '请选择所属系统';
        this.selectedMode = 'single';
        this.maintenanceService.getDepartmentDatas().subscribe(res => {
          this.filesTree4 = res;
        });
        break;
      case 'locationOccur':
        this.dialogHeader = '请选择发生地点';
        this.selectedMode = 'single';
        this.maintenanceService.getDepartmentDatas().subscribe(res => {
          this.filesTree4 = res;
        });
        break;
      case 'relativeCategore':
        this.dialogHeader = '请选择关联服务目录';
        this.selectedMode = 'single';
        this.maintenanceService.getDepartmentDatas().subscribe(res => {
          this.filesTree4 = res;
        });
        break;
      case 'relativeEquip':
        this.dialogHeader = '请选择关联设备编号';
        this.selectedMode = 'single';
        this.maintenanceService.getDepartmentDatas().subscribe(res => {
          this.filesTree4 = res;
        });
        break;
      case 'selectedDepartment':
        this.dialogHeader = '请选择部门';
        this.selectedMode = 'single';
        this.maintenanceService.getDepartmentDatas().subscribe(res => {
          this.filesTree4 = res;
        });
        break;
    }
  }
  // 组织树懒加载
  nodeExpand(event) {
    switch ( this.currentTreeName ) {
      case 'reporter':
        if (event.node) {
          this.maintenanceService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
            event.node.children  = res;
          });
        }
        break;
      case 'belongSystem':
        if (event.node) {
          this.maintenanceService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
            event.node.children  = res;
          });
        }
        break;
      case 'locationOccur':
        if (event.node) {
          this.maintenanceService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
            event.node.children  = res;
          });
        }
        break;
      case 'relativeCategore':
        if (event.node) {
          this.maintenanceService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
            event.node.children  = res;
          });
        }
        break;
      case 'relativeEquip':
        if (event.node) {
          this.maintenanceService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
            event.node.children  = res;
          });
        }
        break;
      case 'selectedDepartment':
        if (event.node) {
          this.maintenanceService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
            event.node.children  = res;
          });
        }
        break;
    }
  }
  nodeSelect(event) {
    console.log(event);
  }
  // 清空组织树选中内容
  clearTreeDialog (which) {
    switch ( which ) {
      case 'reporter':
        this.reporter = [];
        break;
      case 'belongSystem':
        this.belongSystem = [];
        break;
      case 'locationOccur':
        this.locationOccur = [];
        break;
      case 'relativeCategore':
        this.relativeCategore = [];
        break;
      case 'relativeEquip':
        this.relativeEquip = [];
        break;
      case 'selectedDepartment':
        this.selectedDepartment = [];
        this.getDepPerson();
        break;
    }
  }
  // 组织树最后选择
  closeTreeDialog() {
    switch ( this.currentTreeName ) {
      case 'reporter':
        this.reporter = this.selected;
        break;
      case 'belongSystem':
        this.belongSystem = this.selected;
        break;
      case 'locationOccur':
        this.locationOccur = this.selected;
        break;
      case 'relativeCategore':
        this.relativeCategore = this.selected;
        break;
      case 'relativeEquip':
        this.relativeEquip = this.selected;
        break;
      case 'selectedDepartment':
        this.selectedDepartment = this.selected;
        this.getDepPerson(this.selected['oid']);
        break;
    }
    this.departementDisplay = false;
  }
  getDepPerson(oid?) {
    this.publicService.getApprovers(oid).subscribe(res => {
      if (!res) {
        this.malDepPersonOptions = [];
      }else {
        this.malDepPersonOptions = res;
      }
    });
  }
  onFocus() {
    this.getPrority();
  }
  // 计算优先级
  getPrority() {
    if ( this.malImpact && this.malUrgency ) {
      this.maintenanceService.getPrority( this.malImpact['name'], this.malUrgency['name'] ).subscribe(res => {
        if (res) {
          this.malfPrority = res['priority'];
          this.getDeadline();
        }
      });

    }
  }
  // 计算最终期限
  getDeadline() {
    if ( this.malImpact && this.malUrgency && this.malfPrority ) {
      this.maintenanceService.getDeadline( this.malImpact['name'], this.malUrgency['name'], this.malfPrority ).subscribe(res => {
        if (res) {
          this.malDeadline = res['deadline'];
        }
      });
    }
  }
  // 日期格式化
  static formatDate(date) {
    if ( date ) {
      return date.getFullYear() +
        '-' + pad( date.getMonth() + 1 ) +
        '-' + pad( date.getDate() ) +
        ' ' + pad( date.getHours() ) +
        ':' + pad( date.getMinutes() ) +
        ':' + pad( (date.getSeconds() / 1000).toFixed() );
    }else {
      return date;
    }
    function pad (num) {
      if ( num < 10 ) {
        return '0' + num;
      }
      return num;
    }

  }
  showError() {
    this.msg = [];
    this.msg.push({severity: 'error', summary: '错误消息提示', detail: '请填写完整表单'});
  }
  submitPost(paper) {
    this.maintenanceService.offTrick( paper ).subscribe(res => {
      if ( res === '00000' ) {
        this.message = [];
        this.message.push({severity: 'success', summary: '消息提示', detail: '操作成功'});
        window.setTimeout(() => {
          this.router.navigateByUrl('/index/maintenance/malfunctionBase');
        }, 1100);

      }else {
        this.message = [];
        this.message.push({severity: 'error', summary: '消息提示', detail: `操作失败${res}`});
      }
    });
  }
//     故障单解决、保存
  close() {

    this.paper['sid'] = this.malfNumber;
    this.paper['close_code'] = this.malClose['name'];
    console.log(this.paper);
    if ( !this.malClose['name'] ) {
      this.showError();
    }else {
      this.submitPost(this.paper);
    }
  }


}
